package com.springboot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.springboot.controller.utils.R;
import com.springboot.domain.Book;
import com.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@Controller(value = "/books")
//在@Controller上加值暂时不知道什么作用，如果想类拦截，应该在该类上加@RequestMapping
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("{currentPage}/{pageSize}")
    public R getAll(@PathVariable("currentPage")Integer currentPage, @PathVariable("pageSize") Integer pageSize,Book book){
        IPage page = bookService.getAll(currentPage, pageSize,book);
        //删除后跳转
//        if(page.getTotal()%pageSize==0)
        //currentPage是前端传过来的,page.getPages是当前实际页码
        if(currentPage>page.getPages())
            page = bookService.getAll(currentPage-1, pageSize,book);

        //添加后跳转
        if(currentPage<page.getPages())
            page=bookService.getAll(currentPage+1,pageSize,book);
        return new R(true,page);
    }

    @PostMapping
    public R insert(@RequestBody Book book){
        bookService.insert(book);
        return new R(true);
    }

    @GetMapping("{id}")
    public R getById(@PathVariable("id") Integer id){
        Book byId = bookService.getById(id);
        return new R(true,byId);
    }

    @PutMapping
    public R update(@RequestBody Book book){
        bookService.updateById(book);
        return new R(true);
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable("id") Integer id){
        bookService.deleteById(id);
        return new R(true);
    }
}
